package com.hro.hro_app.gcm;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.hro.hro_app.R;
import com.hro.hro_app.main.MainActivity;
import com.hro.hro_app.util.Properties;

public class GCMIntentService extends GCMBaseIntentService {

	@Override
	protected void onError(Context arg0, String arg1) {

		Log.i(Properties.TAG, "on error");
	}

	@Override
	protected void onMessage(Context ctx, Intent i) {

		Log.i(Properties.TAG, "on message: " + i.getStringExtra("message"));

		generateNotification(ctx, i.getStringExtra("message"));
	}

	@Override
	protected void onRegistered(Context arg0, String arg1) {

		Log.i(Properties.TAG, "on registered: " + arg1);
	}

	@Override
	protected void onUnregistered(Context arg0, String arg1) {

		Log.i(Properties.TAG, "on unregistered");
	}

	private static void generateNotification(Context context, String message) {

		int icon = R.drawable.ic_launcher;
		long when = System.currentTimeMillis();
		NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		Notification notification = new Notification(icon, message, when);

		String title = context.getString(R.string.app_name);

		Intent notificationIntent = new Intent(context, MainActivity.class);
		// set intent so it does not start a new activity
		notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
		notification.setLatestEventInfo(context, title, message, intent);
		notification.flags |= Notification.FLAG_AUTO_CANCEL;

		// Play default notification sound
		notification.defaults |= Notification.DEFAULT_SOUND;

		// Vibrate if vibrate is enabled
		notification.defaults |= Notification.DEFAULT_VIBRATE;
		notificationManager.notify(0, notification);
	}
}
